<template>
	<!-- 相机 -->
	<camera :device-position="position" flash="auto" v-if="src === ''">
		<cover-view>
			<cover-image src="/static/pic/reverse.png" @tap="reverse"></cover-image>
			<cover-image src="/static/pic/camera.png" @tap="takePhoto"></cover-image>
			<cover-image src="/static/pic/album.png" @tap="choosePhoto"></cover-image>
		</cover-view>
	</camera>

	<!-- 展示照片 -->
	<view class="photo" v-else>
		<image :src="src" mode="aspectFill"></image>
		<button type="default" @tap="reChoose">重选照片</button>
		<!-- 颜值数据 -->
		<view class="faceinfo" v-if="faceinfo.age !== undefined">
			<view class="row">
				<text>年龄：{{ faceinfo.age }}岁</text>
				<text>性别：{{ map.gender[faceinfo.gender.type] }}</text>
			</view>
			<view class="row">
				<text>颜值：{{ faceinfo.beauty }}分</text>
				<text>表情：{{ map.expression[faceinfo.expression.type] }}</text>
			</view>
			<view class="row">
				<text>眼镜：{{ map.glasses[faceinfo.glasses.type] }}</text>
				<text>情绪：{{ map.emotion[faceinfo.emotion.type] }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp()
	export default {
		data() {
			return {
				position: 'back', // 摄像头朝向
				src: '', // 图片路径
				token: '', // 授权token
				faceinfo: {}, // 颜值信息
				globalData: {
					userInfo: app.globalData.userInfo
				},
				// 中英文映射对象
				map: {
					gender: {
						male: '男性',
						female: '女性'
					},
					expression: {
						none: '不笑',
						smile: '微笑',
						laugh: '大笑'
					},
					glasses: {
						none: '无眼镜',
						common: '普通眼镜',
						sun: '墨镜'
					},
					emotion: {
						angry: '愤怒',
						disgust: '厌恶',
						fear: '恐惧',
						happy: '高兴',
						sad: '伤心',
						surprise: '惊讶',
						neutral: '无表情',
						pouty: '撅嘴',
						grimace: '鬼脸'
					}
				}
			}
		},
		onLaunch() {
			// 展示本地存储能力
			const logs = uni.getStorageSync('logs') || []
			logs.unshift(Date.now())
			uni.setStorageSync('logs', logs)
			// 登录
			uni.login({
					success: res => {
						// 发送 res.code 到后台换取 openId, sessionKey, unionId
					}
				}),
				// 获取用户信息
				uni.getSetting({
					success: res => {
						if (res.authSetting['scope.userInfo']) {
							// 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
							uni.getUserInfo({
								success: res => {
									// 可以将 res 发送给后台解码出 unionId
									this.globalData.userInfo = res.userInfo
									// 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
									// 所以此处加入 callback 以防止这种情况
									if (this.userInfoReadyCallback) {
										this.userInfoReadyCallback(res)
									}
								}
							})
						}
					}
				})

		},
		methods: {
			// 切换摄像头
			reverse() {
				this.position = this.position === 'front' ? 'back' : 'front'
			},
			// 拍照
			takePhoto() {
				// 创建相机的上下文对象
				const ctx = uni.createCameraContext()
				// 拍摄照片
				ctx.takePhoto({
					quality: 'high',
					success: res => {
						this.src = res.tempImagePath
						// 获取颜值数据
						this.getFaceInfo()
					}
				})
			},
			// 选择照片
			choosePhoto() {
				uni.chooseImage({
					count: 1,
					sizeType: ['original'],
					sourceType: ['album'],
					success: res => {
						this.src = res.tempFilePaths[0]
						// 获取颜值数据
						this.getFaceInfo()
					}
				})
			},
			// 重新选择
			reChoose() {
				this.src = '',
				this.token = '',
				this.faceinfo = {}
			},
			// 获取颜值数据
			getFaceInfo() {
				uni.showLoading({
					title: '颜值检测中...',
				})
				// 1.发送请求，获取access token
				uni.request({
					method: 'POST',
					url: 'https://aip.baidubce.com/oauth/2.0/token?grant_type=c	lient_credentials&client_id=CKjRnbdubKcL3oYRr0G5y70b&client_secret=9wlcsf0kyEg7w9LMk6zTk0hbHhAKyZPn',
					success: res => {
						this.token = res.data.access_token
						// 2.准备参数
						this.processParams()
					}
				})
			},
			// 处理参数
			processParams() {
				const params = {
					image: '',
					image_type: 'BASE64',
					face_field: 'age,gender,beauty,expression,glasses,emotion'
				}
				// 获取图片数据，以base64格式
				const fileManager = uni.getFileSystemManager()
				fileManager.readFile({
					filePath: this.src,
					encoding: 'base64',
					success: res => {
						params.image = res.data
						// 3.发送请求，检测颜值（人脸检测）
						this.detectFace(params)
					}
				})
			},
			// 检测人脸信息的获取
			detectFace(params) {
				uni.request({
					method: 'POST',
					url: 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + this.token,
					header: {
						'Content-Type': 'application/json'
					},
					data: params,
					success: res => {
						if (res.statusCode === 200 && res.data.error_code === 0) {
							this.faceinfo = res.data.result.face_list[0]
						}
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			}
		}
	}
</script>

<style>
	camera {
		width: 100vw;
		height: 100vh;
	}

	cover-view {
		display: flex;
		justify-content: space-around;
		position: absolute;
		bottom: 100rpx;
		width: 100%;
		z-index: 99;
	}

	cover-image {
		width: 100rpx;
		height: 100rpx;
		opacity: 0.8;
	}

	.photo image {
		width: 100vw;
		height: 100vh;
	}

	.photo button {
		position: absolute;
		bottom: 100rpx;
		left: 50%;
		transform: translate(-50%);
		color: #55aa7f;
	}

	.faceinfo {
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		/*向左向上移动自身位置的50%*/
		width: 80%;
		height: 350rpx;
		background-color: rgba(255, 255, 255, 0.8);
		border-radius: 10rpx;
		box-shadow: 0 6rpx 20rpx white;
		font-size: 24rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
	}

	.faceinfo .row {
		display: flex;
		justify-content: space-around;
	}

	.faceinfo .row text {
		flex: 1;
		/*每个text所占比例为1：1，自动撑满，前提父容器为display：flex*/
		padding-left: 80rpx;
		color: #aa55ff;
		font-size: 27rpx;
	}
</style>